package jp.sourceforge.akjrcp.psp.commands;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;

import jp.sourceforge.akjrcp.psp.PSPIOCommand;
import jp.sourceforge.akjrcp.psp.PSPSyncView;
import jp.sourceforge.akjrcp.util.FileNameUtils;
import jp.sourceforge.akjrcp.util.image.ImageUtils;

public abstract class AbstractIOCommand implements PSPIOCommand{
private File srcFile;
private File destFile;
private boolean pSPSrc;
private boolean canceld;
public boolean isPSPSrc() {
	return pSPSrc;
}
public void setPSPSrc(boolean src) {
	pSPSrc = src;
}
public File getDestFile() {
	return destFile;
}
public void setDestFile(File destFile) {
	this.destFile = destFile;
}
public File getSrcFile() {
	return srcFile;
}
public void setSrcFile(File srcFile) {
	this.srcFile = srcFile;
}

private boolean overwrite;
public boolean isOverwrite() {
return overwrite;
}
public void setOverwrite(boolean overwrite) {
this.overwrite = overwrite;
}
public boolean isCanceld() {
	return canceld;
}
public void setCanceld(boolean canceld) {
	this.canceld = canceld;
}

public File toPSPThumbnailFile(File imgFile){
	if(imgFile!=null && imgFile.exists()){
		/*
		 * check image size;
		 */
		File thumbFile=imgFile;
		try{
		Image checkImage=new Image(null,imgFile.getAbsolutePath());
		if(checkImage!=null){
			//check size;
			if(checkImage.getBounds().width>160 ||checkImage.getBounds().height>120){
				File tmp=File.createTempFile("image", ".jpg");
				tmp.deleteOnExit();
				Image newthumb=ImageUtils.createThumbnail(checkImage, 160, 120);
				
				ImageLoader loader =new ImageLoader();
				loader.data=new ImageData[]{newthumb.getImageData()};
				loader.save(tmp.getAbsolutePath(), SWT.IMAGE_JPEG);
				thumbFile=tmp;
			}
		}else{
			PSPSyncView.log.warn("image is wrong:"+imgFile);	
		}
		}catch(Exception e){
			PSPSyncView.log.warn("image copy faild:"+imgFile);	
			e.printStackTrace();
		}
		return thumbFile;
		
	}else{
		return null;
	}
}
/*
 * this method make a file just moment
 */
public static boolean canWrite(File file){
	boolean canwrite=false;
	if(file.exists()){
		canwrite=file.canWrite();
	}else{
		try {
			FileUtils.touch(file);
		} catch (IOException e) {
		}
		if(file.exists()){
			canwrite=file.delete();//maybe no need.
		}else{
			//it faild writing.
		}
		
	}
	return canwrite;
}

}
